package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic/v7"
	"strconv"
	"time"
	"week2_zg6/bookRpc/book"
	"week2_zg6/bookRpc/internal/svc"
	"week2_zg6/common/es"
	"week2_zg6/common/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearcherLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearcherLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearcherLogic {
	return &SearcherLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

type Book struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore float64 `json:"max_score"`
		Hits     []struct {
			Index  string  `json:"_index"`
			Type   string  `json:"_type"`
			Id     string  `json:"_id"`
			Score  float64 `json:"_score"`
			Source struct {
				ID        int         `json:"ID"`
				CreatedAt time.Time   `json:"CreatedAt"`
				UpdatedAt time.Time   `json:"UpdatedAt"`
				DeletedAt interface{} `json:"DeletedAt"`
				BookName  string      `json:"BookName"`
				Author    string      `json:"Author"`
				Class     string      `json:"Class"`
				Title     string      `json:"Title"`
			} `json:"_source"`
		} `json:"hits"`
	} `json:"hits"`
}

func (l *SearcherLogic) Searcher(in *book.SearcherRequest) (*book.SearcherResponse, error) {
	serrch, err := es.Client.Search("book").Query(elastic.NewMatchQuery("BookName", in.Searcher)).Do(context.Background())

	if err != nil {
		return nil, err
	}
	indent, err := json.MarshalIndent(serrch, "", "")
	if err != nil {
		return nil, err
	}
	var books Book
	fmt.Println(mysql.Book{})
	err = json.Unmarshal(indent, &books)
	if err != nil {
		return nil, err
	}
	return &book.SearcherResponse{
		Id:       strconv.Itoa(books.Hits.Hits[0].Source.ID),
		BookName: books.Hits.Hits[0].Source.BookName,
		Author:   books.Hits.Hits[0].Source.Author,
		Class:    books.Hits.Hits[0].Source.Class,
		Title:    books.Hits.Hits[0].Source.Title,
	}, nil
}
